<!-- tinymce富文本编辑器组件 -->
<template>
  <div>
    <editor v-model="content" :value="value" :init="config" :disabled="disabled" />
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
// import 'tinymce/icons/default'
import { $upload } from "@/utils/http"
import 'tinymce/themes/silver'
import 'tinymce/plugins/code'
import 'tinymce/plugins/print'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/save'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/link'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/quickbars'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/emoticons/js/emojis'

export default {
  name: 'TinymceEditor',
  components: { Editor },
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: String,
    init: Object,
    disabled: Boolean,
  },
  data() {
    return {
      content: '',
      moldslist: [], //模块列表
      showEdit: false, // 是否显示表单弹窗
      form: {}, // 表单数据
      rules: {
        // 表单验证规则
        mold: [{ required: true, message: '请选择mold表名', trigger: 'blur' }],
        field: [
          { required: true, message: '请输入field字段', trigger: 'blur' },
        ],
      },
      fieldslist: [], //fields字段列表
      loading: false, // 加载状态
      mold_field: '',
      myEditor: null, //定义editor的全局变量
      config: Object.assign(
        {
          height: 300,
          branding: false,
          skin_url: '/tinymce/skins/ui/oxide',
          content_css: '/tinymce/skins/content/default/content.css',
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          plugins:
            'code print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
          toolbar:
            'fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap anchor pagebreak codesample | ltr rtl | assignment',	//加入定义的按钮名到工具栏
          toolbar_drawer: 'sliding',
          // 图片上传
          images_upload_handler: (blobInfo, success, error) => {
            let file = blobInfo.blob()
            const formData = new FormData()
            formData.append('file', file, file.name)
            $upload(formData).then((res) => {
              // console.log(res);
              let { errno, errmsg, url } = res;
              if (errno !== 200) return error(res)
              success(url)
            })
              .catch((e) => {
                console.error(e)
                error(e.message)
              })
          },
          //images_upload_handler: (blobInfo, success) => {
          //console.log(blobInfo)
          //success('data:image/jpeg;base64,' + blobInfo.base64());
          //},
          //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
          //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
          //   images_upload_handler: (blobInfo, success, failure) => {
          //     const img = "data:image/jpeg;base64," + blobInfo.base64();
          //     success(img);
          //   },
          file_picker_types: 'media',
          file_picker_callback: () => { },
          setup: (editor) => {
            let _this = this
            _this.myEditor = editor
            //定义一个名为 assignment 的toolbar
            editor.ui.registry.addButton('assignment', {
              text: `<i class="el-icon-position" style="font-size: 18px"></i>`,
              tooltip: '赋值',
              onAction: () => {
                _this.showEdit = true
              },
            })
          },
        },
        this.init
      ),
    }
  },
  methods: {
    //获得所有模块数据
    // getmoldslist() {
    //   this.$http
    //     .get('/molds/getmyall?nouser=1')
    //     .then((res) => {
    //       if (res.data.code === 0) {
    //         this.moldslist = res.data.data
    //       } else {
    //         this.$message.error(res.data.msg)
    //       }
    //     })
    //     .catch((e) => {
    //       this.$message.error(e.message)
    //     })
    // },
    //选择模块时触发的事件
    chooseMold(val) {
      if (val != null && val != '') {
        // console.log(val)
        this.$http
          .get('/fields/getmyall?molds=' + val.toString())
          .then((res) => {
            if (res.data.code === 0) {
              this.fieldslist = res.data.data
              // console.log(this.fieldslist)
            } else {
              this.$message.error(res.data.msg)
            }
          })
          .catch((e) => {
            this.$message.error(e.message)
          })
      }
    },
    //保存模块选中的值
    save() {
      let _this = this
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          _this.showEdit = false
          //将模块名和字段名拼接，格式：模块名_字段名
          _this.mold_field = '#' + _this.form.mold + '_' + _this.form.field + '#'
          console.log(_this.mold_field)
          _this.myEditor.insertContent(_this.mold_field)
        } else {
          return false
        }
      })
    },
  },
  mounted() {
    tinymce.init({})
    // this.getmoldslist()
  },
  watch: {
    content() {
      this.$emit('change', this.content)
    },
    value() {
      this.content = this.value
    },
  },
}
</script>

<style>
body .tox-tinymce-aux {
  z-index: 19892000;
}
</style>
 